package com.vpen.account.demo.utils;

import cn.hutool.core.util.StrUtil;
import com.vpen.account.demo.handler.AccountDemoException;
import com.vpen.account.demo.model.dto.CodeDto;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadLocalRandom;

/**
 * 描述
 *
 * @author 韦鹏
 * @date 2022/8/16 14:44
 */
@Component
public class CodeUtils {

    public static final String BASE_NUMBER = "01234567899876543210";

    private static RedissonClient REDISSON;

    @Autowired
    private void setRedisson(RedissonClient redisson) {
        REDISSON = redisson;
    }

    /**
     * 获取redis
     *
     * @return org.redisson.api.RedissonClient
     * @author 韦鹏
     * @date 2022/8/16 18:07
     **/
    public static RedissonClient getRedisson() {
        return REDISSON;
    }


    /**
     * 获取随机验证码
     *
     * @return com.vpen.account.demo.model.dto.CodeDto
     * @author 韦鹏
     * @date 2022/8/16 14:02
     **/
    public static CodeDto getRandomNum() {
        StringBuilder sb = new StringBuilder(6);
        for (int i = 0; i < 6; i++) {
            int num = ThreadLocalRandom.current().nextInt(BASE_NUMBER.length());
            sb.append(BASE_NUMBER.charAt(num));
        }
        return new CodeDto(sb.toString(), System.currentTimeMillis());
    }


    /**
     * 校验验证码
     *
     * @param phone 手机号
     * @param code  验证码
     * @return boolean
     * @author 韦鹏
     * @date 2022/8/16 12:39
     **/
    public static boolean validCode(String phone, String code) {
        RBucket<CodeDto> codeBucket = REDISSON.getBucket(phone);
        // 1.验证码是否存在
        if (!codeBucket.isExists()) {
            throw new AccountDemoException("验证码校验失败");
        }
        // 2.验证码是否相等
        if (!StrUtil.equals(codeBucket.get().getCode(), code)) {
            return false;
        }
        // 3.验证通过删除
        codeBucket.deleteAsync();
        return true;
    }

    /**
     * 两次生成验证码的时间是否小于60秒
     *
     * @param timeStamp 开始时间
     * @return boolean
     * @author 韦鹏
     * @date 2022/8/16 11:58
     **/
    public static boolean validTime(long timeStamp) {
        return (System.currentTimeMillis() - timeStamp) < 60_000L;
    }
}
